package com.ruoyi.web.controller.system;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.hyperledge.chaincode.Invokecode;
import com.ruoyi.hyperledge.dto.DataDTO;
import com.ruoyi.hyperledge.dto.FileDTO;
import com.ruoyi.system.domain.standard_relevant.DataFile;
import com.ruoyi.system.domain.standard_relevant.DataOperLog;
import com.ruoyi.system.service.standard.IDataFileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;



/**
 * 文件上传 控制层
 * @author Lion Li
 */
@RestController
@RequestMapping("/oss")
public class SysOssController extends BaseController {

    @Autowired
    private IDataFileService dataFileService;

    @Autowired
    private Invokecode invokecode;
    private static final MinioClient minioClient =
            MinioClient.builder()
                    .endpoint("http://59.77.5.3:9001")
                    .credentials("minio", "minio123")
                    .build();

    public static final String URL = "http://59.77.5.3:9001/influence/";


    /**
     * 上传OSS对象存储
     * @param file 文件
     */

    @ApiOperation("上传文件")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult upload(@RequestParam("file") MultipartFile file, HttpServletRequest data) {
        //存文件
        if (ObjectUtils.isEmpty(file)) {
//            return R.fail("上传文件不能为空");
            AjaxResult.error("上传文件不能为空");
        }
        String originalFileName = file.getOriginalFilename();

        String url =URL+ originalFileName;

        try
        {
            /**
             *  是否为需要记录新增操作
             */
            boolean needRecord = false;

            /**
             * 上传supplement 需要:
             * id(自增)，dataName(参数),status('2'),remark(参数),dataType('supplement'),excelPath(null),standardCode(参数),filesPath(+=url)
             */
            Long id = Long.parseLong("0");
            String dataName = data.getParameter("dataName");// 数据名称
            String remark = data.getParameter("remark");// 备注
            String standardCode = data.getParameter("standardCode");// 标准号
            String stage = data.getParameter("stage");// 阶段名称
            System.out.println("data"+data);
            /**
             * 存文件 相关操作
             */
            try {
                PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                        .bucket("influence")
                        .object(originalFileName) // 使用原始文件名作为对象名
                        .stream(file.getInputStream(), file.getSize(), -1) // 文件输入流、大小
                        .contentType(file.getContentType()) // 设置文件类型
                        .build();
                minioClient.putObject(putObjectArgs);
            } catch (Exception e) {
                throw new GlobalException(e.getMessage());
            }
            /**
             *
             * 存入数据库时
             */
            /** 记录 indicator-filePath 的关系，后转为JSON 保存*/
            Map<String, List<String>> filesPathMap = new HashMap<>();
            DataFile dataFile = dataFileService.selectDataFileByDataName(dataName);

            // 获取当前时间
            LocalDateTime nowTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String currentDateTime = nowTime.format(formatter);
            LocalDateTime parsedDateTime = LocalDateTime.parse(currentDateTime, formatter);
            Date now_time = java.sql.Timestamp.valueOf(parsedDateTime);

            // 获取当前用户名
            String user = SecurityUtils.getLoginUser().getUsername();

            /**
             * 第一次存   那就新增
             */
            if (dataFile == null) {
                needRecord = true;// 日志--新增数据
                List<String> urlList = new ArrayList<>();
                urlList.add(url);
                filesPathMap.put(stage, urlList);
                JSONObject filesPath = new JSONObject(filesPathMap);
                DataFile new_dataFile_supplement = new DataFile(id, dataName, "2", remark, "supplement", null, standardCode, filesPath.toJSONString());


                FileDTO fileDTO = new FileDTO()
                        .setFileName(originalFileName).setFilePath(url)
                        .setOperUser("admin1").setOperTime(String.valueOf(now_time)).setOperType("新建");
                List<FileDTO> files =new ArrayList<>();
                files.add(fileDTO);
                Map<String,List<FileDTO>> stages =new HashMap<>();
                stages.put(stage,files);
                DataDTO dataDTO = new DataDTO()
                        .setDataName(dataName)
                        .setStandardCode(standardCode)
                        .setRemark(remark)
                        .setStages(stages);
                try {
                    dataFileService.insertDataFile(new_dataFile_supplement);
                    invokecode.createData(dataDTO);
                } catch (Exception e) {
                    return AjaxResult.error(e.getMessage());
                }
            }/**
             *  非第一次存    更新 filesPath
             */
            else {
                String filesPath_Old = dataFile.getFilesPath();
                JSONObject filesPath_New = JSONObject.parseObject(filesPath_Old);

                if(filesPath_New.containsKey(stage)){
                    List<String> urlList = filesPath_New.getJSONArray(stage).toJavaList(String.class);
                    urlList.add(URL);
                    filesPath_New.put(stage, urlList);
                }else{
                    List<String> urlList = new ArrayList<>();
                    urlList.add(URL);
                    filesPath_New.put(stage, urlList);
                }
                DataFile update_dataFile_supplement = new DataFile(dataFile.getId(), dataName, "2", remark, "supplement", null, standardCode, filesPath_New.toJSONString());
                FileDTO fileDTO = new FileDTO()
                        .setFileName(originalFileName).setFilePath(URL)
                        .setOperUser(user).setOperTime(String.valueOf(now_time)).setOperType("新建");
                try {
                    dataFileService.updateDataFile(update_dataFile_supplement);
                    invokecode.updateData(dataName,stage,"",fileDTO);
                } catch (Exception e) {
                    return AjaxResult.error(e.getMessage());
                }
            }

            /**
             * 插入 数据操作日志 ---- 新增数据
             */
            if(needRecord){
                String content ="{\"新增数据\": {\"after\": \""+dataName+"\", \"before\": \"\"}}";;
                DataOperLog dataOperLog = new DataOperLog(Long.parseLong("0"), "新增", dataName, content, "admin",now_time );
                try{
                    dataFileService.insertDataOperLog(dataOperLog);
                }catch (Exception e){
                    return AjaxResult.error(e.getMessage());
                }
            }


            /**
             * 返回结果
             */
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", URL+ originalFileName);
            ajax.put("fileName", originalFileName);
            ajax.put("newFileName", originalFileName);
            ajax.put("originalFilename", originalFileName);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
//        return R.ok(URL + originalFileName);
    }
}
